/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.ShopFacade;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.util.StringConverter;
import jfxtras.labs.scene.control.BeanPathAdapter;
import jpamodel.Category;
import jpamodel.CommissionWare;
import jpamodel.OwnedWare;
import jpamodel.Seller;

/**
 *
 * @author Hans
 */
public class NewWareView extends GridPane {

    private Text commission, owned;
    private TextField comName, comPrice, ownName, ownPurchase, ownPrice;
    private ComboBox<Seller> sellerCombo;
    private Button addCommission, addOwnWare;
    private ShopFacade shop;
    private ObservableList<Seller> sellerList;// = FXCollections.observableArrayList(sellers);
    private ComboBox<Category> categoryCombo, categoryCombo2;
    private DatePicker comDatePicker, ownDatePicker;
    private final ObservableList<CommissionWare> commissionList;
    private final ObservableList<OwnedWare> ownWareList;

    public NewWareView(ObservableList<Seller> sellers, ObservableList<OwnedWare> ownWareList, ObservableList<CommissionWare> commissionList, ShopFacade shop) {
        this.sellerList = sellers;
        this.commissionList = commissionList;
        this.ownWareList = ownWareList;
        this.shop = shop;
        comDatePicker = newDatePicker();
        ownDatePicker = newDatePicker();
        setPadding(MainView.INSETS);
        setHgap(10);
        setVgap(10);
        categoryCombo = new ComboBox<>();
        //  categoryCombo;
        categoryCombo.setPromptText("Vælg Kategori");
        categoryCombo.getStyleClass().add("combobox");
        categoryCombo2 = new ComboBox<>();
        categoryCombo2.setPromptText("Vælg Kategori");
        categoryCombo2.getStyleClass().add("combobox");
        commission = new Text("* Ny Kommission *");
        commission.setFont(MainView.getFont());
        owned = new Text("* Egen Vare *");
        owned.setFont(MainView.getFont());
        comName = new TextField();
        comPrice = new IntegerTextField();
        ownName = new TextField();
        ownPurchase = new IntegerTextField();
        ownPrice = new IntegerTextField();
        sellerCombo = new ComboBox<>();
        sellerCombo.getStyleClass().add("combobox");
        sellerCombo.setItems(this.sellerList);
        Seller seller = new Seller();
        BeanPathAdapter<Seller> sellerAdapter = new BeanPathAdapter<>(seller);
        sellerAdapter.bindBidirectional("name", sellerCombo.valueProperty(), Seller.class);
        categoryCombo.setItems(shop.getCategories(true));
        categoryCombo2.setItems(shop.getCategories(true));
        sellerCombo.setPromptText("Vælg Sælger");
        setupButtons();
        this.addRow(0, commission);
        this.addRow(1, new Label("Vare Navn"), new Label("Sælger"), new Label("Pris"), new Label("Dato"));
        this.addRow(2, comName, sellerCombo, comPrice, comDatePicker);
        this.addRow(3, addCommission, categoryCombo);
        this.addRow(4, new Rectangle(1, 100, Color.BLACK.deriveColor(1, 1, 1, 0)));
        this.addRow(10, owned);
        this.addRow(11, new Label("Vare Navn"), new Label("Indkøb"), new Label("Pris"), new Label("Dato"));
        this.addRow(12, ownName, ownPurchase, ownPrice, ownDatePicker);
        this.addRow(13, addOwnWare, categoryCombo2);
        setupComboBoxes();
    }

    private boolean validateCommisionWare() {
        boolean result = true;
        if (comName.getText().trim().isEmpty()
                || comPrice.getText().trim().isEmpty()
                || sellerCombo.getValue() == null
                || categoryCombo.getValue() == null) {
            TextFieldValidation.setRed(comName);
            TextFieldValidation.setRed(comPrice);
            ComboBoxValidation.setRed(sellerCombo);
            ComboBoxValidation.setRed(categoryCombo);
            result = false;
        }
        return result;
    }

    public boolean validateOwnedWare() {
        boolean result = true;
        if (ownName.getText().trim().isEmpty()
                || ownPrice.getText().trim().isEmpty()
                || ownPurchase.getText().trim().isEmpty()
                || categoryCombo2.getValue() == null) {
            TextFieldValidation.setRed(ownName);
            TextFieldValidation.setRed(ownPrice);
            TextFieldValidation.setRed(ownPurchase);
            ComboBoxValidation.setRed(categoryCombo2);
            result = false;
        }
        return result;
    }

    public void update() {
        if (shop.getDBC().isConnected()) {
            sellerList.removeAll(shop.getAllSellers());
            sellerList.clear();
            sellerList.addAll(shop.getAllSellers());
        }
    }
    
    
    
    private void setupComboBoxes() {
        sellerCombo.setCellFactory((comboBox) -> {
            return new ListCell<Seller>() {
                @Override
                protected void updateItem(Seller item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item.getName());
                    }
                }
            };
        });
        sellerCombo.setConverter(new StringConverter<Seller>() {
            @Override
            public String toString(Seller seller) {
                if (seller == null) {
                    return null;
                } else {
                    return seller.getName();
                }
            }

            @Override
            public Seller fromString(String personString) {
                return null;
            }
        });
        
        categoryCombo.setCellFactory((comboBox) -> {
            return new ListCell<Category>() {
                @Override
                protected void updateItem(Category item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item.getName() + " (" + item.getCommissionWareList().size() + ")");
                    }
                }
            };
        });
        categoryCombo.setConverter(new StringConverter<Category>() {
            @Override
            public String toString(Category category) {
                if (category == null) {
                    return null;
                } else {
                    return category.getName() + " (" + category.getCommissionWareList().size() + ")";
                }
            }

            @Override
            public Category fromString(String personString) {
                return null;
            }
        });
        categoryCombo2.setCellFactory((comboBox) -> {
            return new ListCell<Category>() {
                @Override
                protected void updateItem(Category item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item.getName() + " (" + item.getOwnedWareList().size() + ")");
                    }
                }
            };
        });
        categoryCombo2.setConverter(new StringConverter<Category>() {
            @Override
            public String toString(Category category) {
                if (category == null) {
                    return null;
                } else {
                    return category.getName() + " (" + category.getOwnedWareList().size() + ")";
                }
            }

            @Override
            public Category fromString(String personString) {
                return null;
            }
        });
    }

    private void setupButtons() {
        addCommission = new Button("Tilføj ny Kommission");
        addCommission.getStyleClass().add("mybutton");
        addCommission.setOnAction(event -> {
            if (validateCommisionWare()) {
                CommissionWare cware = new CommissionWare();
                cware.setName(comName.getText());
                cware.setCurrentPrice(Integer.parseInt(comPrice.getText()));
                cware.setCategory(categoryCombo.getValue());
                cware.setLocalDateIn(comDatePicker.getValue());
                cware.setSeller(sellerCombo.getValue());
                shop.persist(cware);
            }
        });
        addOwnWare = new Button("Tilføj ny Egen Vare");
        addOwnWare.getStyleClass().add("mybutton");
        addOwnWare.setOnAction(event -> {
            if (validateOwnedWare()) { //make a check to see that data is complete
                OwnedWare ownedWare = new OwnedWare();
                ownedWare.setName(ownName.getText());
                ownedWare.setPurchasePrice(Integer.parseInt(ownPurchase.getText()));
                ownedWare.setSoldPrice(Integer.parseInt(ownPrice.getText()));
                ownedWare.setCategory(categoryCombo2.getValue());
                ownedWare.setDateIn(ownDatePicker.getValue());
                shop.persist(ownedWare);
            }
        });
    }

    public final DatePicker newDatePicker() {
        DatePicker newDatePicker = new DatePicker(LocalDate.now());
        newDatePicker.setOnAction(event -> {
            LocalDate date = comDatePicker.getValue();
        });
        newDatePicker.setConverter(new StringConverter<LocalDate>() {
            String pattern = "dd-MM-yyyy";
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

            @Override
            public String toString(LocalDate date) {
                if (date != null) {
                    return dateFormatter.format(date);
                } else {
                    return "";
                }
            }

            @Override
            public LocalDate fromString(String string) {
                if (string != null && !string.isEmpty()) {
                    return LocalDate.parse(string, dateFormatter);
                } else {
                    return null;
                }
            }
        });
        return newDatePicker;
    }

}
